import { Module } from 'vuex';

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login';
import localCache from '@/utils/cache';
import { mapMenustoRoutes, mapMenusToPermissions } from '@/utils/map-menu';
import router from '@/router';

import { ILoginState } from './types';
import { IRootState } from '../types';
import { IAccount } from '@/service/login/types';

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    };
  },
  mutations: {
    // 保存token
    changeToken(state, token: string) {
      state.token = token;
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus;

      // userMenus -> routes
      const routes = mapMenustoRoutes(userMenus);
      // 将routes -> routes.main.children
      routes.forEach((route) => {
        router.addRoute('main', route);
      });

      // 按钮权限
      const permissions = mapMenusToPermissions(userMenus);
      state.permissions = permissions;
    }
  },
  getters: {},
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      // 1.实现登录逻辑
      const loginResult = await accountLoginRequest(payload);
      const { id, token } = loginResult.data;
      commit('changeToken', token);
      localCache.setCache('token', token);

      // 发送初始化的请求(role/department)
      dispatch('getInitialDataAction', null, { root: true });

      // 2.请求用户信息
      const userInfoResult = await requestUserInfoById(id);
      const userInfo = userInfoResult.data;
      commit('changeUserInfo', userInfo);
      localCache.setCache('userInfo', userInfo);

      // 3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id);
      const userMenus = userMenusResult.data;
      commit('changeUserMenus', userMenus);
      localCache.setCache('userMenus', userMenus);

      // 4.跳到首页
      router.push('/main');
    },
    // 进去main页面后刷新,自动取用本地缓存的数据
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token');
      if (token) {
        commit('changeToken', token);
        // 发送初始化的请求(role/department)
        dispatch('getInitialDataAction', null, { root: true });
      }

      const userInfo = localCache.getCache('userInfo');
      if (userInfo) {
        commit('changeUserInfo', userInfo);
      }

      const userMenus = localCache.getCache('userMenus');
      if (userMenus) {
        commit('changeUserMenus', userMenus);
      }
    }
    // phoneLoginAction({ commit }, payload: any) {
    //   console.log('phoneLoginAction', payload);
    // }
  }
};

export default loginModule;
